package fr.pioug.gdocs.service;

import java.io.*;
import java.util.*;

import org.apache.commons.lang.*;

import fr.pioug.gdocs.object.*;

/**
 * @author a011228
 * @version
 */
public class LocalService {

	private static LocalService mLocalService = null;

	private LocalService() {

	}

	/**
	 * @return
	 */
	public static LocalService getInstance() {
		if (mLocalService == null) {
			mLocalService = new LocalService();
		}
		return mLocalService;
	}

	/**
	 * @param pPathToSave
	 * @return
	 */
	public GDocsFile getTree(String pPathToSave) {
		GDocsFile lLocalTree = buildTree(new File(pPathToSave), true,
				pPathToSave);
		return lLocalTree;
	}

	private GDocsFile buildTree(File pDirectory, boolean pTreeRoot,
			String pPathToSave) {

		GDocsFile lDocsDirectory = new GDocsFile(pDirectory, pTreeRoot);
		lDocsDirectory.setPath(StringUtils.replace(pDirectory.getParent(),
				pPathToSave, ""));
		lDocsDirectory.setAbsolutePath(pDirectory.getAbsolutePath());

		if (pDirectory != null) {
			List<GDocsFile> lList = new ArrayList<GDocsFile>();
			for (File lFile : pDirectory.listFiles()) {
				if (lFile.isDirectory()) {
					lList.add(buildTree(lFile, false, pPathToSave));
				} else {
					if (GDocsService.isFileValid(lFile)) {
						GDocsFile lDocsFileTmp = new GDocsFile(lFile);
						lDocsFileTmp.setPath(StringUtils.replace(lFile
								.getParent(), pPathToSave, ""));
						lDocsFileTmp.setAbsolutePath(lFile.getAbsolutePath());
						lList.add(lDocsFileTmp);
					}
				}
			}
			lDocsDirectory.setListGDocs(lList);
		}
		return lDocsDirectory;
	}
}
